<?php

/**
 * 前端活动Function
 */
include_once('class/setting.php' );
include_once('class/medoo.min.php');

function new_meddo() {

    $mysql = new medoo(
            array(
        'database_type' => 'mysql',
        'database_name' => MYSQL_DATABASE,
        'server' => MYSQL_SERVER,
        'username' => MYSQL_USER,
        'password' => MYSQL_PASSWORD,
            )
    );
    return $mysql;
}

/**
 * 数据增加
 * @param type $table
 * @param type $fields
 * @return type
 */
function insert($table, $fields) {
    $mysql = new_meddo();
    $id = $mysql->insert($table, $fields);
    $error = $mysql->error();
    if ($error[0] != '00000') {
        print_r($error);
        return array('status' => FALSE);
    } else {
        return array('status' => TRUE, 'mid' => $id);
    }
}

/**
 * 判断用户登陆
 * @param type $username
 * @param type $password
 * @return boolean
 */
function user_login($username, $password) {
    if ($username == 'admin' && $password == 'admin') {
        return TRUE;
    } else {
        return FALSE;
    }
}

/**
 * 新增奖品
 * @param type $fields
 * @return type
 */
function insert_parize($fields) {
    $mysql = new_meddo();
    $id = $mysql->insert(TABLE_C_PRIZE, $fields);
    $error = $mysql->error();
    if ($error[0] != '00000') {
        print_r($error);
        return array('status' => FALSE);
    } else {
        return array('status' => TRUE, 'id' => $id);
    }
}

/**
 * 新增中奖日
 * @param type $fields
 * @return type
 */
function insert_parize_day($fields) {
    $mysql = new_meddo();
    $id = $mysql->insert(TABLE_C_PRIZE_DAY, $fields);
    $error = $mysql->error();
    if ($error[0] != '00000') {
        print_r($error);
        return array('status' => FALSE);
    } else {
        return array('status' => TRUE, 'id' => $id);
    }
}

/**
 * 
 * @param type $fields
 * @return type
 */
function insert_user_form($fields) {

    $mysql = new_meddo();
    $id = $mysql->insert(TABLE_C_PRIZE_FORM, $fields);
    $error = $mysql->error();
    if ($error[0] != '00000') {
        print_r($error);
        return array('status' => FALSE);
    } else {
        return array('status' => TRUE, 'id' => $id);
    }
}

function insert_user_form_code10($fields) {
    $mysql = new_meddo();
    $id = $mysql->insert(TABLE_C_PRIZE_FORM_C10, $fields);
    $error = $mysql->error();
    if ($error[0] != '00000') {
        print_r($error);
        return FALSE;
    } else {
        return TRUE;
    }
}

function insert_user_form_code20($fields) {
    $mysql = new_meddo();
    $id = $mysql->insert(TABLE_C_PRIZE_FORM_C20, $fields);
    $error = $mysql->error();
    if ($error[0] != '00000') {
        print_r($error);
        return FALSE;
    } else {
        return TRUE;
    }
}

function insert_user_form_code50($fields) {
    $mysql = new_meddo();
    $id = $mysql->insert(TABLE_C_PRIZE_FORM_C50, $fields);
    $error = $mysql->error();
    if ($error[0] != '00000') {
        print_r($error);
        return FALSE;
    } else {
        return TRUE;
    }
}

function insert_user_form_userinfo($fields) {

    $mysql = new_meddo();
    $id = $mysql->insert(TABLE_C_PRIZE_FORM_USERINFO, $fields);
    $error = $mysql->error();
    if ($error[0] != '00000') {
        print_r($error);
        return array('status' => FALSE);
    } else {
        return array('status' => true, 'id' => $id);
    }
}

//=============================================================================>FIND
/**
 * 查询所以奖品
 * @return type
 */
function find_all_parize() {
    $mysql = new_meddo();
    $result = $mysql->select(TABLE_C_PRIZE, "*");
    $error = $mysql->error();
    if ($error[0] != '00000') {
        print_r('Mysql error: ' . $error[2]);
    }
    return $result ? $result : 0;
}

/**
 * 查询所以奖品CODE
 * @return type
 */
function find_all_code() {
    $mysql = new_meddo();
    $result = $mysql->select(TABLE_C_CODE, "*");
    $error = $mysql->error();
    if ($error[0] != '00000') {
        print_r('Mysql error: ' . $error[2]);
    }
    return $result ? $result : 0;
}

function find_user_info_only_one($openid) {

    $mysql = new_meddo();
    $query = "SELECT * FROM `campaign_prize_form_userinfo` as cp WHERE cp.openid='" . $openid . "' LIMIT 1;";
    $result = $mysql->query($query)->fetch();
    $error = $mysql->error();
    if ($error[0] != '00000') {
        print_r('Mysql error: ' . $error[2]);
    }

    return !empty($result) ? $result : 0;
}

function find_user_allinfo_by_openid($openid) {
    $mysql = new_meddo();
    $query = "SELECT cp.is_big_prize,cp.prize_name,cp.prize_type,cp1.code_10,cp1.code_10_code,cp2.code_20,cp2.code_20_code,cp3.code_50,cp3.code_50_code FROM `campaign_prize_form_userinfo` as cp
LEFT JOIN campaign_prize_form_code10 as cp1 ON cp.openid=cp1.openid
LEFT JOIN campaign_prize_form_code20 as cp2 ON cp.openid=cp2.openid
LEFT JOIN campaign_prize_form_code50 as cp3 ON cp.openid=cp3.openid
WHERE cp.openid='" . $openid . "' LIMIT 1;";

    $result = $mysql->query($query)->fetch();

    $error = $mysql->error();
    if ($error[0] != '00000') {
        print_r('Mysql error: ' . $error[2]);
    }
    return $result ? $result : 0;
}

/**
 * 查询奖品CODE
 * @return type
 */
function find_parize_code($pid) {
    $mysql = new_meddo();
    $where = array('parize_id' => $pid);
    $result = $mysql->select(TABLE_C_CODE, "*", $where);
    $error = $mysql->error();
    if ($error[0] != '00000') {
        print_r('Mysql error: ' . $error[2]);
    }
    return $result ? $result : 0;
}

/**
 * 查询所有中奖日
 * @return type
 */
function find_parize_day($day) {
    $mysql = new_meddo();

    $where = array('AND' => array('day' => $day, 'is_big_win' => 1), 'ORDER' => 'prize_rate asc');
    $result = $mysql->select(TABLE_C_PRIZE_DAY, "*", $where);
    $error = $mysql->error();
    if ($error[0] != '00000') {
        print_r('Mysql error: ' . $error[2]);
    }
    return $result ? $result : 0;
}

/**
 * 查询活动当天中奖数
 * @param type $prize_type
 * @return type
 */
function find_sum_day_info($prize_type) {
    $mysql = new_meddo();
    $sql1 = "SELECT SUM(prize_num) prize_num ,SUM(prize_num1) win_num FROM " . TABLE_C_PRIZE_DAY . " WHERE prize_type=" . $prize_type;
    $result = $mysql->query($sql1)->fetch();
    $error = $mysql->error();
    if ($error[0] != '00000') {
        print_r('Mysql error: ' . $error[2]);
    }
    return $result ? $result : 0;
}

/**
 * 查询剩余天数
 * @return type
 */
function find_prize_get_day1() {
    $date = date("Y-m-d ", time()); //当前时间
    $pieces = explode("-", $date); //切割字符串
    $time = $pieces[0] . '-' . $pieces[1] . '-' . $pieces[2];
    $select_day = strtotime($time . ' 0:00:00'); //当前日期
//    var_dump($select_day);
//    exit;

    $mysql = new_meddo();
    $where = array('day[>=]' => $select_day);
    $result = $mysql->select(TABLE_C_PRIZE_DAY, "*", $where);
    $error = $mysql->error();
    if ($error[0] != '00000') {
        print_r('Mysql error: ' . $error[2]);
    }
    $day = array();
    $day[0] = '请选择活动时间';
    foreach ($result as $k => $v) {
        $day[$v['day']] = date("Y-m-d ", $v['day']);
    }
    return $day;
}

/**
 * 查询当天奖池数据
 * @param type $day
 * @return type
 */
function find_prize_get_day_info($day) {
    $mysql = new_meddo();
    $sql = "SELECT a.*,b.prize_total FROM " . TABLE_C_PRIZE_DAY . " a LEFT JOIN " . TABLE_C_PRIZE . " b ON a.prize_name=b.prize_name WHERE day=" . $day;
    $result = $mysql->query($sql)->fetchAll();


    $results = array();
    $i = 0;
    foreach ($result as $v) {

        $results[$i]['prize_type'] = $v['prize_type'];
        $results[$i]['prize_name'] = $v['prize_name'];
        $results[$i]['prize_total'] = $v['prize_total'];
        $results[$i]['prize_rate'] = $v['prize_rate'];
        $results[$i]['prize_num'] = $v['prize_num'];
        $results[$i]['win_num'] = $v['prize_num1'];
        $result1 = Sum_prize_winnum($v['prize_type']);
        $results[$i]['win_num_t'] = $result1['win_num'];
        $i++;
    }
    return $results;
}

/**
 * 数据求合
 * @param type $prize_type
 * @return type
 */
function Sum_prize_winnum($prize_type) {
    $mysql = new_meddo();
    $sql1 = "SELECT SUM(prize_num1) win_num FROM " . TABLE_C_PRIZE_DAY . " WHERE prize_type=" . $prize_type;
    $result = $mysql->query($sql1)->fetch();
    return $result;
}

function find_all_user() {
    $mysql = new_meddo();
    $result = $mysql->select(TABLE_C_PRIZE_FORM, "*");
    $error = $mysql->error();
    if ($error[0] != '00000') {
        print_r('Mysql error: ' . $error[2]);
    }
    return $result ? $result : 0;
}

function find_userinfo_byid($codeid = null) {

    if (empty($codeid)) {
        return null;
    }

    $temp_id = explode('D', $codeid);
    $temp_id2 = explode('H', $temp_id[1]);
    $id = $temp_id2[0];


    $mysql = new_meddo();
    $where = array('id' => $id);
    $result = $mysql->select(TABLE_C_PRIZE_FORM, "*", $where);
    $error = $mysql->error();
    if ($error[0] != '00000') {
        print_r('Mysql error: ' . $error[2]);
    }
    return $result ? $result[0] : 0;
}

function find_userinfo_by_openid($openid = null) {

    if (empty($openid)) {
        return 0;
    }

    $mysql = new_meddo();
    $where = array('openid' => $openid);
    $result = $mysql->select(TABLE_C_PRIZE_FORM_USERINFO, "*", $where);
    $error = $mysql->error();
    if ($error[0] != '00000') {
        print_r('Mysql error: ' . $error[2]);
    }
    return $result ? $result[0] : 0;
}

//==============================================================================>UPDATE

function win_update($id, $prize_num1) {
    $mysql = new_meddo();
    $where = array('id' => $id);
    $data = array('prize_num1' => $prize_num1);
    $result = $mysql->update(TABLE_C_PRIZE_DAY, $data, $where);
    return $result;
}

function user_info_update($id, $data) {
    $mysql = new_meddo();
    $where = array('id' => $id);
    $result = $mysql->update(TABLE_C_PRIZE_FORM_USERINFO, $data, $where);
    return $result;
}

/**
 * 更新奖品总数
 * @param type $condition
 * @param type $parameter
 * @return type
 */
function prize_update_total($condition, $parameter) {
    $mysql = new_meddo();
    $result = $mysql->update(TABLE_C_PRIZE, $parameter, $condition);

    return $result;
}

/**
 * 活动投放数据
 * @param type $condition
 * @param type $parameter
 * @return type
 */
function prize_update_day($condition, $parameter) {
    $mysql = new_meddo();
    $result = $mysql->update(TABLE_C_PRIZE_DAY, $parameter, $condition);

    return $result;
}

//==============================================================================CLEAR


function clear($type) {
    $table = '';
    if ($type == 1) {
        $table = TABLE_C_PRIZE_DAY;
    } elseif ($type == 2) {
        $table = TABLE_C_PRIZE;
    } elseif ($type == 3) {
        $table = TABLE_C_PRIZE_FORM;
    }


    if (!empty($table)) {
        $mysql = new_meddo();
        $sql = 'TRUNCATE TABLE ' . $table;
        $result = $mysql->query($sql)->fetch();
        return $result;
    }
}

//==============================================================================WIN
/**
 * 用户是否已中大奖
 * @param type $mobile
 * @return boolean
 */
function user_iswin($openid = null) {

    if (empty($openid)) {
        return TRUE;
    }
    $mysql = new_meddo();
    $where = array('AND' => array('openid' => $openid, 'is_big_prize' => 1));
    $result = $mysql->count(TABLE_C_PRIZE_FORM_USERINFO, $where);
    if ($result != 0) {
        return TRUE;
    } else {
        return FALSE;
    }
}

function iswin($openid) {
    $date = date("Y-m-d ", time()); //当前时间    
    $select_day = strtotime($date . ' 0:00:00'); //格式化当前日期
    $user_iswin = user_iswin($openid);

    if (!$user_iswin) {
        //可以参加大奖
        $prize_rate = find_parize_day($select_day, $user_iswin);

        $total = 0;
        foreach ($prize_rate as $value) {
            $total+=$value['prize_rate'];
        }

        $ran_num = rand(0, $total); //随机数

        $current = 0;
        $prize_type = 0;
        $prize_name = '';
        $prize_num1 = 0;
        for ($i = 0; $i < count($prize_rate); $i++) {
            if ($ran_num >= $current && ($prize_rate[$i]['prize_rate'] + $current) > $ran_num) {
                if ($prize_rate[$i]['prize_num'] > $prize_rate[$i]['prize_num1'] && $prize_rate[$i]['is_big_win']) {
                    $prize_type = $prize_rate[$i]['prize_type'];
                    $prize_name = $prize_rate[$i]['prize_name'];
                    $id = $prize_rate[$i]['id'];
                    $prize_num1 = $prize_rate[$i]['prize_num1'];
                }
                break;
            } else {
                $current+=$prize_rate[$i]['prize_rate'];
            }
        }

        //判断是否大中奖，如没有，出小奖
        if (!empty($id)) {
            $status = win_update($id, $prize_num1 + 1);
            if ($status) {
                return array(
                    'prize_type' => $prize_type,
                    'prize_name' => $prize_name,
                    'day' => $select_day,
                    'is_big_prize' => 1
                );
            } else {
                return '';
            }
        } else {
            return '';
        }
    } else {
        return '';
    }
}

/**
 * 中code
 * @param type $openid
 */
function win_code($openid) {
    $mysql = new_meddo();

    $query1 = "SELECT code_10 FROM campaign_prize_form_code10 WHERE openid='" . $openid . "' limit 1";
    $query2 = "SELECT code_20 FROM campaign_prize_form_code20 WHERE openid='" . $openid . "' limit 1";
    $query3 = "SELECT code_50 FROM campaign_prize_form_code50 WHERE openid='" . $openid . "' limit 1";

    $result1 = $mysql->query($query1)->fetchAll();
    $result2 = $mysql->query($query2)->fetchAll();
    $result3 = $mysql->query($query3)->fetchAll();

    $prize_type = array();

    if ($result1[0]['code_10'] == 0) {
        $prize_type[] = 'code_10';
    }
    if ($result2[0]['code_20'] == 0) {
        $prize_type[] = 'code_20';
    }
    if ($result3[0]['code_50'] == 0) {
        $prize_type[] = 'code_50';
    }


    if (empty($prize_type)) {
        return array('is_win' => 0, 'info' => '没有中奖');
    }
    //看有几个可以中奖的code
    $temp_count_prize = count($prize_type);
    $temp_count_prize2 = $temp_count_prize - 1;
    if ($temp_count_prize2 < 0) {
        return array('is_win' => 0, 'info' => '没有中奖');
    }
    //产生随机数看中哪个烦
    $ran_num = rand(0, $temp_count_prize2); //随机数
    $win_type = $prize_type[$ran_num];
    //产生code随机数
    $ran_num_code = rand(0, 8);
    $ran_code = '';



    switch ($win_type) {
        case 'code_10':
            $code_10 = array('69ANQRXY','345AJRST','3DFNPTUW','4EGHLSUX','25CGMNUV','5ACEFMUY','26FGJNUW','249CFGJK','5CEKNTVZ');
            $ran_code = $code_10[$ran_num_code];
            $fields_code10=array();
            $fields_code10['openid'] = $openid;
            $fields_code10['created'] = time();
            $fields_code10['code_10'] = 1;
            $fields_code10['code_10_code'] = $ran_code;
            insert_user_form_code10($fields_code10);
            break;
        case 'code_20':
            $code_20 = array('24CDHPQU','7EHKQVXZ','349CFKPQ','25AFLNTY','25CDGJKN','34CEFJPS','46AEFGSV','234HNPSX','27ARSUVY');
            $ran_code = $code_20[$ran_num_code];
            $fields_code20=array();
            $fields_code20['openid'] = $openid;
            $fields_code20['created'] = time();
            $fields_code20['code_20'] = 1;
            $fields_code20['code_20_code'] = $ran_code;
            insert_user_form_code20($fields_code20);

            break;
        case 'code_50':
            $code_50 = array('569ADGHS','9CKLNRSV','345ADLPS','24AHJKRY','6FGHPSVY','2349CKWX','6FGMQUWZ','DFJKPUWX','569GJKPV');
            $ran_code = $code_50[$ran_num_code];
            $fields_code30=array();
            $fields_code30['openid'] = $openid;
            $fields_code30['created'] = time();
            $fields_code30['code_50'] = 1;
            $fields_code30['code_50_code'] = $ran_code;
            insert_user_form_code50($fields_code30);
            break;
    }
    return array('is_win' => 1, 'info' => 'ok', 'prize_type' => $win_type, 'code' => $ran_code);
}

function create_share_id($uid) {
    $string1 = creat_ran_code(3);
    $string2 = creat_ran_code(3);
    return $string1 . 'D' . $uid . 'H' . $string2;
}

/**
 * 创建code
 * @param type $str_long
 * @return type
 */
function creat_ran_code($str_long = 8) {
    $strarr = array('1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'E', 'F', 'G', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y');
    $strarr_num = count($strarr) - 1;
    $code_str = '';
    for ($i = 0; $i < $str_long; $i++) {
        $ran_num = rand(0, $strarr_num);
        $code_str.=$strarr[$ran_num];
    }
//    //9363
//    $code_num = substr(time(), -4);

    return $code_str;
}

//==============================================================================>图片生成
/**
 * 生成图片BEST64->IMAGE
 * @param stdClass $image
 * @return type
 */
function best64_image($image_show = null, $image_share = null) {
//    print_r($image);
    $image_name = time();
    //图片1
    $ciy1 = check_image_type($image_show);
    if (!$ciy1['status']) {
        return $ciy1;
    }
    $image_type1 = $ciy1['image_type'];
    $filter_arr1 = $ciy1['filter_arr'];
    $image_code1 = $filter_arr1[1];
    $image_root1 = ROOT_PATH . 'user_image/images_show/';

    $s1 = base64_decode($image_code1);
    file_put_contents($image_root1 . $image_name . $image_type1, $s1);
    $image1_url = BEST_PATH . 'user_image/images_show/' . $image_name . $image_type1;

    //图片2
    $ciy2 = check_image_type($image_share);
    if (!$ciy1['status']) {
        return $ciy2;
    }
    $image_type2 = $ciy2['image_type'];
    $filter_arr2 = $ciy2['filter_arr'];
    $image_code2 = $filter_arr2[1];
    $image_root2 = ROOT_PATH . 'user_image/images_share/';
    $s2 = base64_decode($image_code2);
    file_put_contents($image_root2 . $image_name . $image_type2, $s2);
    $image2_url = BEST_PATH . 'user_image/images_share/' . $image_name . $image_type2;

    $image = new stdClass();
    $image->image_show = $image1_url;
    $image->image_share = $image2_url;

    return array("status" => 1, 'data' => $image);
}

/**
 * 检查图片格式
 * @param type $image
 * @return type
 */
function check_image_type($image) {
    if (empty($image)) {
        return array('status' => 0, 'msg' => 'Missing parameter:Image');
    }

    //判断图片格式
    $filter_arr = explode(',', $image);
    if (!isset($filter_arr[1]) || empty($filter_arr[1])) {
        return array("status" => 0, 'msg' => 'Data format error.');
    }
    $image_data_arr = explode(';', $filter_arr[0]);
    if (!isset($image_data_arr[1]) || empty($image_data_arr[1]) || $image_data_arr[1] != 'base64') {
        return array("status" => 0, 'msg' => 'Non-base64 encoded format.');
    }
    $image_type_arr = explode(':', $image_data_arr[0]);
    if (!isset($image_type_arr[1]) || empty($image_type_arr[1]) || ($image_type_arr[1] != 'image/png' && $image_type_arr[1] != 'image/jpg' && $image_type_arr[1] != 'image/jpeg')) {
        return array("status" => 0, 'msg' => 'Please upload a PNG or JPG format picture format.');
    }
    $image_type = '';
    if ($image_type_arr[1] == 'image/jpg' || $image_type_arr[1] == 'image/jpeg') {
        $image_type = '.jpg';
    } elseif ($image_type_arr[1] == 'image/png') {
        $image_type = '.png';
    }
    return array('status' => 1, 'msg' => 'OK', 'image_type' => $image_type, 'filter_arr' => $filter_arr);
}

function get_web_page($url) {
    $options = array(
        CURLOPT_RETURNTRANSFER => true, // return web page
        CURLOPT_HEADER => false, // don't return headers
        CURLOPT_FOLLOWLOCATION => true, // follow redirects
        CURLOPT_ENCODING => "", // handle all encodings
        CURLOPT_USERAGENT => "spider", // who am i
        CURLOPT_AUTOREFERER => true, // set referer on redirect
        CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
        CURLOPT_TIMEOUT => 120, // timeout on response
        CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
        CURLOPT_SSL_VERIFYPEER => false     // Disabled SSL Cert checks
    );
    $ch = curl_init($url);
    curl_setopt_array($ch, $options);
    $content = curl_exec($ch);
    $err = curl_errno($ch);
    $errmsg = curl_error($ch);
    $header = curl_getinfo($ch);
    curl_close($ch);
    $header['errno'] = $err;
    $header['errmsg'] = $errmsg;
    $header['content'] = $content;
    return $header;
}
